package openones.samples.dataform.biz;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import openones.samples.dataform.entity.User;
import openones.samples.dataform.form.AddInForm;
import rocky.common.CommonUtil;
import rocky.common.Constant;

/**
 * Demo business class.
 * @author Thach Le
 *
 */
public class DataFormBiz {
    static final Logger LOG = Logger.getLogger("DataFormBiz");
    static Map<String, User> userMap = new HashMap<String, User>();
    
    /**
     * Add user.
     * @param user
     */
    public void addUser(User user) {
        userMap.put(user.getUsername(), user);
        LOG.debug("Added a new user '" + user + "'. Total " + userMap.size() + " users.");
    }

    public void addUser(AddInForm userForm) {
        User user = convF2E(userForm);
        userMap.put(user.getUsername(), user);
        LOG.debug("Added a new user '" + user + "'. Total " + userMap.size() + " users.");
    }
    
    /**
     * @param userForm
     * @return
     */
    private User convF2E(AddInForm userForm) {
        User user = new User();
        user.setUsername(userForm.getUsername());
        user.setBirthday(CommonUtil.parse(userForm.getBirthday(), Constant.VN_DATEFMT));
        user.setAddress(userForm.getAddress());
        user.setPicture(userForm.getAttachedFile());
        if (CommonUtil.isNNandNB(userForm.getToeflMark())) {
            user.setToelfMark(Integer.parseInt(userForm.getToeflMark()));
        }
        
        return user;
    }

    /**
     * Get all users.
     * @return
     */
    public Collection<User>  getUsers() {
        return userMap.values();
    }
}
